import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { ReuseTabService } from '@delon/abc';
import { ApiService } from '@core/api.service';
import { FarmReactComponent } from '../../../layout/components/farmreact.component';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { DatePipe } from '@angular/common';
import { StatusFollowService } from '@core/statusFollow.service';
import { _HttpClient } from '@delon/theme';
import { HttpParams, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../../environments/environment';

@Component({
  selector: 'app-examconstructionplansg',
  templateUrl: './examconstructionplan_sg.component.html',
  styleUrls: ['./examconstructionplan_sg.component.less']
})
export class ExamconstructionplanSgComponent implements OnInit {
  @ViewChild('farmReact', { static: true }) farmReact: FarmReactComponent;
  examData: any = [];
  pageValue = '50';
  selectedValue = '50';
  rowPage = 1;
  pageIndex = 1;
  rowTotal = 0;
  pageTotal = '';
  displayData = [];
  allChecked = false;
  indeterminate = false;
  drrqValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
  zyrqStartValue: any;
  zyrqEndValue: any;
  drwxVisible = false;
  ppczVisible = false;
  ldspVisible = false;
  ppczIds = '';
  ldspValue = '';
  ldspSelect: any = [];
  planTypes = '';
  planEdit = false;
  planView = false;
  listOfOption: any = [];
  listOfTagOptions = [];
  listOptionsString = '';
  approval = false;
  ratifyRejectVisible = false;
  ratifyRejectTitle = '';
  ratifyRejectText = '';
  ratifyRejectType = '';
  ratifyRejectStatus = '';
  ratifyFenpi = '0';
  ShenpiMessage = '';
  shopsign = false;
  shopbatches = false;
  adjustorg = '';
  buttonType = '';
  sgDataTemp = true;
  lockHeadScroll = { x: '3600px', y: window.innerHeight - 325 + 'px' };
  selectedDataLen = 0;
  modifyGqModal = false;
  stationSelect: any = [];
  userInfo = JSON.parse(this.ls.get('loginInfo'));
  ppStation: any = ''; // 修改某条目匹配系统站时需要用到
  workarea: any = [];
  ppWorkareaid: any = '';
  modifyNid: any = '';

  constructor(
    private apiService: ApiService,
    public msg: NzMessageService,
    private activatedRoute: ActivatedRoute,
    public ls: LocalStorage,
    private reuseTabService: ReuseTabService,
    private statusFollowService: StatusFollowService,
    private http: _HttpClient,
    private datePipe: DatePipe
  ) { }

  ngOnInit() {
    this.listOfOption = [
      { value: '-1', label: '全选' },
      { value: '0', label: '计划已导入' },
      { value: '1', label: '调度审批中' },
      { value: '2', label: '调度已批准' },
      { value: '3', label: '调度已驳回' },
      { value: '4', label: '车间已签收' },
      { value: '5', label: '车间编制中' },
      { value: '6', label: '车间已下发' },
      { value: '7', label: '工区已签收' },
      { value: '8', label: '工区已提报' },
      { value: '9', label: '车间已审核' },
      { value: '10', label: '车间已驳回' },
      { value: '11', label: '调度已批准' },
      { value: '12', label: '调度已驳回' },
      { value: '13', label: '小结已填写' }
    ];
    for (const item of this.listOfOption) {
      this.listOfTagOptions.push(item.value);
    }
    this.activatedRoute.params.subscribe((params: Params) => {
      if (params.status == 'view' || params.status == 'today') {
        this.reuseTabService.title = '日施工计划';
        this.planView = true;
      }
      if (params.status == 'edit') {
        this.planTypes = 'diaodu';
        this.buttonType = 'edit';
        this.reuseTabService.title = '施工计划导入';
        this.planEdit = true;
      }
      if (params.status == 'leaderapproval') {
        this.planTypes = 'dld';
        this.buttonType = 'leaderapproval';
        this.reuseTabService.title = '施工计划审批';
        this.approval = true;
      }
      if (params.status == 'shopsign') {
        this.planTypes = 'cjqs';
        this.reuseTabService.title = '施工计划签收'; // 20191011 zhangz
        // this.reuseTabService.title = "天窗计划签收";
        this.shopsign = true;
      }
      if (params.status == 'shopbatches') {
        this.planTypes = 'cjfp';
        this.reuseTabService.title = '施工计划分批'; // 20191011 zhangz
        // this.reuseTabService.title = "天窗计划分批";
        this.shopbatches = true;
      }
      if (params.status == 'today') {
        this.zyrqStartValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
        this.zyrqEndValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
      } else {
        this.zyrqStartValue = this.datePipe.transform(new Date().getTime() + 86400000, 'yyyy-MM-dd');
        this.zyrqEndValue = this.datePipe.transform(new Date().getTime() + 86400000, 'yyyy-MM-dd');
      }
      this.getWorkarea();
      this.readyload(this.rowPage, this.pageValue);
    });
  }

  _onReuseInit() {
    this.readyload(this.rowPage, this.pageValue);
  }

  listCheck(callback) {
    this.ppczIds = '';
    this.displayData.forEach(data => {
      if (data.checked) {
        this.ppczIds += ',' + data.N_ID;
      }
    });
    if (this.ppczIds == '') {
      this.msg.error('请选择一条数据进行操作', { nzDuration: 1000 });
      callback(false);
    } else {
      if (this.ppczIds) {
        this.ppczIds = this.ppczIds.replace(',', '');
      }
      callback(true);
    }
  }

  statusFollow(data) {
    return this.statusFollowService.init('1', data);
  }

  // 导入维修日计划
  drwxPop() {
    this.drwxVisible = true;
  }

  drwxOk() {
    this.getintosgrwx_sg(this.drrqValue).subscribe((res: any) => {
      if (res.type === 'success') {
        this.msg.success('提交成功', { nzDuration: 1000 });
        this.drwxVisible = false;
        this.drrqValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
        this.readyload(this.rowPage, this.pageValue);
      } else {
        this.msg.error('提交失败', { nzDuration: 1000 });
      }
    });
  }

  // 施工日维修导入列表
  getintosgrwx_sg(begindate) {
    const url = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/getintosgrsg.jwt?begindate=' + this.datePipe.transform(begindate, 'yyyy-MM-dd');
    return this.http.get(url);
  }

  drwxCancel() {
    this.drwxVisible = false;
  }

  // 匹配系统车站
  ppczPop() {
    this.listCheck((check) => {
      if (check) {
        this.ppczVisible = true;
      }
    });
  }

  ppczOk() {
    this.farmReact.childOuter((res) => {
      if (res.chezhanValue == '0') {
        this.msg.error('请选择车站', { nzDuration: 1000 });
        return;
      }
      this.updatesgrwx_sg(this.ppczIds, res.chezhanValue, res.gongquValue).subscribe((data: any) => {
        if(typeof(data) !== 'object'){
          data = JSON.parse(data);
        }
        if (data.type === 'success') {
          this.msg.success('提交成功', { nzDuration: 1000 });
          this.ppczVisible = false;
          this.ppczIds = '';
          this.farmReact.clearAll();
          this.readyload(this.rowPage, this.pageValue);
        } else {
          this.msg.error('提交失败', { nzDuration: 1000 });
        }
      });
    });
  }

  // 提交匹配系统车站
  updatesgrwx_sg(ids, vcSta, vcOrgId) {
    const url = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/updateSgxtrsg.jwt';
    const params = new HttpParams()
      .set('ids', ids)
      .set('vcSta', vcSta)
      .set('vcOrgId', vcOrgId);
    return this.http.post(url, params);
  }

  ppczCancel() {
    this.ppczVisible = false;
  }

  // 提交领导审批
  ldspPop() {
    this.listCheck((check) => {
      if (check) {
        const rows: any = this.displayData.filter((el) => this.ppczIds.includes(el.N_ID));
        if (rows && rows.length) {
          let illegalExist = false;
          rows.forEach(row => {
            if ((!row.STANAME) || (!row.ORGNAME)) {

              illegalExist = true;
            }
          });
          if (illegalExist) {
            this.msg.error('勾选项目中存在 无匹配系统站 和 工区的条目，请先对这些条目进行匹配车站操作', { nzDuration: 3000 });
          } else {
            this.ldspVisible = true;
          }
        }
      }
    });
    this.apiService.getDldPerson('KMBUR_KMNSEG_ORG_40').subscribe((res: any) => {
      this.ldspSelect = res;
      this.ldspValue = res[0].opValue;
    });
  }

  ldspOk() {
    this.apiService.updatesgrwxPerson_sg(this.ppczIds, this.ldspValue, '1', this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss'), '', '').subscribe((res: any) => {
      if (JSON.parse(res).type === 'success') {
        this.msg.success('提交成功', { nzDuration: 1000 });
        this.ldspVisible = false;
        this.ppczIds = '';
        this.ldspValue = '';
        this.readyload(this.rowPage, this.pageValue);
      } else {
        this.msg.error('提交失败', { nzDuration: 1000 });
      }
    });
  }

  ldspCancel() {
    this.ldspVisible = false;
  }

  // 批准&驳回
  ratifyReject(type) {
    this.listCheck((check) => {
      if (check) {
        this.ratifyRejectType = type;
        switch (type) {
          case 'ratify':
            this.ratifyRejectTitle = '确认批准';
            this.ratifyRejectText = '批准';
            this.ratifyRejectStatus = '2';
            break;
          case 'reject':
            this.ratifyRejectTitle = '确认驳回';
            this.ratifyRejectText = '驳回';
            this.ratifyRejectStatus = '3';
            break;
        }
        this.ratifyRejectVisible = true;
      }
    });
  }

  ratifyRejectOk() {
    if (this.ratifyFenpi == '1') {
      this.dayworkfenpi_sg(this.ppczIds).subscribe((res: any) => {
        this.ratifyRejectVisible = false;
        if (res.type === 'success') {
          this.msg.success('分劈成功', { nzDuration: 1000 });
          this.ratifyRejectVisible = false;
          this.ppczIds = '';
          this.ShenpiMessage = '';
          this.ratifyRejectStatus = '';
          this.adjustorg = '';
          this.ratifyFenpi = '0';
          this.readyload(this.rowPage, this.pageValue);
        } else {
          this.msg.error('分劈失败', { nzDuration: 1000 });
        }
      });
    } else {
      this.apiService.updatesgrwxPerson_sg(this.ppczIds, JSON.parse(this.ls.get('loginInfo')).VC_NUMBER, this.ratifyRejectStatus, this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss'), this.ShenpiMessage, this.adjustorg).subscribe((res: any) => {
        if (JSON.parse(res).type === 'success') {
          this.msg.success('提交成功', { nzDuration: 1000 });
          this.ratifyRejectVisible = false;
          this.ppczIds = '';
          this.ShenpiMessage = '';
          this.ratifyRejectStatus = '';
          this.adjustorg = '';
          this.readyload(this.rowPage, this.pageValue);
        } else {
          this.msg.error('提交失败', { nzDuration: 1000 });
        }
      });
    }
  }

  // 施工日维修计划分批
  dayworkfenpi_sg(ids) {
    const url = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/getintoPhTcons.jwt?ids=' + ids;
    return this.http.get(url);
  }

  ratifyRejectCancel() {
    this.ratifyRejectVisible = false;
  }

  // 车间签收
  shopsignPop() {
    this.listCheck((check) => {
      if (check) {
        this.ratifyRejectTitle = '确认车间签收';
        this.ratifyRejectText = '签收';
        this.ratifyRejectStatus = '4';
        this.ratifyRejectVisible = true;
      }
    });
  }

  adjustWork(type) {
    this.listCheck((check) => {
      if (check) {
        switch (type) {
          case 'shop': // 调整到车间
            this.ratifyRejectText = '调整到车间';
            this.adjustorg = '0';
            break;
          case 'work': // 调整到工区
            this.ratifyRejectText = '调整到工区';
            this.adjustorg = '1';
            break;
          case 'batches': // 确认分批
            this.ratifyRejectText = '确认分劈计划';
            this.ratifyFenpi = '1';
            break;
        }
        this.ratifyRejectTitle = '车间分批';
        this.ratifyRejectStatus = 'shopbatches';
        this.ratifyRejectVisible = true;
      }
    });
  }

  getWorkarea(workshopId?) {
    this.apiService.getgongquByCjId(workshopId || '').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      let delIndex;
      for (let i = 0; i < _data.length; i++) {
        const el = _data[i];
        if (!el.opValue) {
          delIndex = i;
        }
      }
      _data.splice(delIndex, 1);
      this.workarea = _data;
    });
  }
  workareaChange(id) {
    this.getStation(id);
  }
  // 获取车站列表
  getStation(id?, staId?) {
    this.ppStation = '';
    this.stationSelect = [];
    this.apiService.getStationByOrgId(id || '', '1').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      this.formatTreeNodes(_data);
      this.stationSelect = _data;
      this.ppStation = staId;
    });
  }

  formatTreeNodes(nodes) {
    if (nodes.length) {
      nodes.forEach(node => {
        node.key = node.opValue || '';
        node.title = node.opName || '';
        if (node.childselectOptions && node.childselectOptions.length) {
          node.isLeaf = false;
          node.children = node.childselectOptions;
          this.formatTreeNodes(node.childselectOptions);
        } else {
          node.isLeaf = true;
        }
      });
    }
  }

  showModifyGq() {
    this.listCheck((check) => {
      if (!check) {
        return;
      }
      if (this.ppczIds.indexOf(',') != -1) {
        this.msg.warning('只能选择一个进行操作');
        return;
      } else {
        const rows: any[] = this.displayData.filter((el) => this.ppczIds.includes(el.N_ID));
        if (rows && rows.length) {
          const row = rows[0];
          this.modifyGqModal = true;
          this.ppWorkareaid = row.VC_ORG$ID;
          this.ppStation = row.VC_STA;
          this.modifyNid = row.N_ID;
          this.getStation(row.VC_ORG$ID, row.VC_STA);
        }
      }
    });
  }

  hideModifyGq() {
    this.modifyGqModal = false;
  }

  modifyGq() {
    if (!this.modifyNid || !this.ppStation || !this.ppWorkareaid) {
      this.msg.warning('请选择工区和车站');
      return;
    }
    this.matchWastaWork_sg(this.modifyNid, this.ppStation, this.ppWorkareaid).subscribe((res: any) => {
      if (typeof (res) == 'string') {
        res = JSON.parse(res);
      }
      if (res && res.type === 'success') {
        this.msg.success('修改成功');
        this.hideModifyGq();
        this.readyload(this.rowPage, this.pageValue);
      } else {
        this.msg.warning('修改失败');
      }
    });
  }

  // 修改匹配系统车站-车间用户
  matchWastaWork_sg(nid, vcSta, vcOrgId) {
    const url = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/matchWastaWork.jwt';
    const params = new HttpParams()
      .set('nid', nid)
      .set('vcSta', vcSta)
      .set('vcOrgId', vcOrgId);
    return this.http.post(url, params);
  }

  // 状态
  listOfTagChange(list) {
    setTimeout(() => {
      for (const item of list) {
        if (item == '-1') {
          this.listOfTagOptions = [];
          this.listOptionsString = '';
          for (const data of this.listOfOption) {
            this.listOfTagOptions.push(data.value);
          }
          break;
        } else {
          this.listOptionsString = this.listOfTagOptions.join(',');
        }
      }
    }, 500);
  }

  readyload(page, rows) {
    this.zyrqStartValue = this.datePipe.transform(this.zyrqStartValue, 'yyyy-MM-dd');
    this.zyrqEndValue = this.datePipe.transform(this.zyrqEndValue, 'yyyy-MM-dd');
    if (!this.listOfTagOptions.length) {
      this.listOptionsString = '';
    }
    this.pageIndex = page;
    this.apiService.finddayworksgrwx_sg(this.planTypes, this.listOptionsString, '', '', '', this.datePipe.transform(this.zyrqStartValue, 'yyyy-MM-dd'), this.datePipe.transform(this.zyrqEndValue, 'yyyy-MM-dd'), page, rows).subscribe((res: any) => {
      if (res.type === 'success') {
        this.examData = res.data.pageList;
        this.pageTotal = res.data.pageCount;
        this.rowTotal = res.data.pageCount;
        if (this.planView && this.sgDataTemp && JSON.parse(this.ls.get('loginInfo')).N_LEVEL == 50 && !this.examData.length) {
          this.sgDataLoad(this.zyrqStartValue, page, rows);
        }
        this.sgDataTemp = false;
      }
    });
  }

  sgDataLoad(date, page, rows) {
    this.getintosgrwx_sg(this.datePipe.transform(date, 'yyyy-MM-dd')).subscribe((res: any) => {
      if (res.type === 'success') {
        this.apiService.finddayworksgrwx_sg(this.planTypes, this.listOptionsString, '', '', '', this.datePipe.transform(this.zyrqStartValue, 'yyyy-MM-dd'), this.datePipe.transform(this.zyrqEndValue, 'yyyy-MM-dd'), page, rows).subscribe((res: any) => {
          if (res.type === 'success') {
            this.examData = res.data.pageList;
            this.pageTotal = res.data.pageCount;
            this.rowTotal = res.data.pageCount;
          }
        });
      } else {
        this.msg.error('导入明天数据出错', { nzDuration: 1000 });
      }
    });
  }

  yearselectedChange() {
    this.pageValue = this.selectedValue;
    this.readyload(this.rowPage, this.pageValue);
  }

  rowChangeTable1(ev) {
    this.rowPage = ev;
    this.readyload(this.rowPage, this.pageValue);
  }

  currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
    this.displayData = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    const allChecked = this.examData.every(value => value.checked == true);
    const allUnChecked = this.examData.every(value => !value.checked);
    this.selectedDataLen = this.examData.filter(v => v.checked).length;
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  // 可以选中多条
  checkAll(value: boolean): void {
    this.examData.forEach(data => data.checked = value);
    this.refreshStatus();
  }

  // 删除多条数据
  delItems() {
    if (this.allChecked || this.indeterminate) {
      const recognition = 'N_ID';
      const delGoodsOrders: string[] = this.examData
        .filter(data => data.checked).map(data => data[recognition]);
      const delList: string[] = [];
      this.examData.forEach(data =>
        delGoodsOrders.includes(data[recognition]) && delList.push(data)
      );
      this.apiService.delMaterialsData('examconstructionplan_sg', delList.map(data => data[recognition]))
        .subscribe(response => {
          if (response.type === 'success') {
            this.msg.success(response.message, { nzDuration: 1800 });
          } else if (response.type === 'fail') {
            this.msg.warning(response.message, { nzDuration: 1500 });
          }
          this.readyload(1, this.pageValue);
        });
    } else {
      this.msg.warning('请先选择待删除数据！', { nzDuration: 1000 });
    }
  }
}
